package com.pgy.general.config;


import com.pgy.general.interceptor.AuthenticationInterceptor;
import com.pgy.general.util.PathUtil;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.*;


/**
 * 开启Mvc,自动注入spring容器。 WebMvcConfigurerAdapter：配置视图解析器
 * 当一个类实现了这个接口（ApplicationContextAware）之后，这个类就可以方便获得ApplicationContext中的所有bean
 *
 * @author xiangze
 *
 */

@Configuration
//// 等价于<mvc:annotation-driven/>
@EnableWebMvc
public class MvcConfiguration  implements WebMvcConfigurer, ApplicationContextAware {
    // Spring容器
    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }


    //配置拦截器
    @Bean
    public AuthenticationInterceptor authenticationInterceptor() {
        return new AuthenticationInterceptor();
    }
    String[] swaggerExcludes=new String[]{"/swagger-resources/**","/v3/**","/swagger-ui/**", "/static/**"};
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authenticationInterceptor()).addPathPatterns("/**").excludePathPatterns(swaggerExcludes).excludePathPatterns("/file/**");
        WebMvcConfigurer.super.addInterceptors(registry);
    }
    //路径映射
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //swagger资源映射
        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/static/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");
        //路径映射
        //存储文件路径映射
        registry.addResourceHandler("/file/**").addResourceLocations("file:"+ PathUtil.getResultPath());
        //本地静态资源映射
        registry.addResourceHandler("/module/**").addResourceLocations("classpath:/module/");
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/templates/**").addResourceLocations("classpath:/templates/");
    }



    //添加全局的配置 允许跨域请求
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT","PATCH")
                .maxAge(3600);
    }
}
